<template>
  <div class="user-management-container">

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入用户名"
        clearable
        style="width: 200px; margin-right: 10px"
        @clear="fetchUserList"
      />
      <el-button type="primary" @click="fetchUserList">搜索</el-button>
      <el-button type="success" @click="handleAddUser">新增用户</el-button>
    </div>

    <!-- 用户列表 -->
    <el-table :data="userList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="nickname" label="昵称" width="120" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="role" label="角色" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{row}">
          {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm') }}
        </template>
      </el-table-column>
      <!-- 在表格中添加头像列 -->
      <el-table-column label="头像" width="120">
        <template #default="{row}">
            <el-avatar :src="row.avatar" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditUser(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchUserList"
        @current-change="fetchUserList"
      />
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="form.nickname" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {getUsers} from '@/api/userManage'
import {addUser} from '@/api/userManage'
import {updateUser} from '@/api/userManage'
import {deleteUser} from '@/api/userManage'
// 在script setup顶部添加
import dayjs from 'dayjs'

// 用户列表数据
const userList = ref([]);
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const dialogTitle = ref('新增用户');
const form = ref(initFormData());

// 初始化表单数据
function initFormData() {
  return {
    id: null,
    username: '',
    nickname: '',
    email: '',
    role: '',
    avatar: '' // 确保包含头像字段
  };
}


// 获取用户列表
const fetchUserList = async () => {
  try {
   const response = await getUsers({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value
    });

    if(response.data.code == 200){ 
      userList.value = response.data.data.list
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
};

// 新增用户弹窗
const handleAddUser = () => {
  form.value = initFormData();
  dialogTitle.value = '新增用户';
  dialogVisible.value = true;
};

// 编辑用户弹窗
const handleEditUser = (user) => {
  form.value = { ...user };
  dialogTitle.value = '编辑用户';
  dialogVisible.value = true;
};

// 提交表单（新增/编辑）
const handleSubmit = async () => {
  try {
    let response;
    
    if (form.value.id) {
      // 编辑用户：传递完整对象，API会从中提取id
      response = await updateUser({
        ...form.value,
        id: form.value.id // 确保包含id字段
      });
    } else {
      // 新增用户
      
      response = await addUser(form.value);
      console.log(form.value)
    }

    if (response.data.code == 200) {
      ElMessage.success(form.value.id ? '编辑成功' : '新增成功');
      dialogVisible.value = false;
      await fetchUserList();
    }
  } catch (error) {
    // 打印详细错误信息
    console.error('操作失败:', error); 
    ElMessage.error({
      message: `操作失败: ${error.response?.data?.message || error.message}`,
      duration: 3000
    });
  }
};

// 删除用户
const handleDeleteUser = async (user) => {
  try {
    await ElMessageBox.confirm('确定删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const response = await deleteUser(user.id);

    if (response.data.code == 200) {
      ElMessage.success('删除成功');
      await fetchUserList(); // 刷新列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};


// 初始化加载用户列表
onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>